import IsWeixinOrAlipay from "./IsWeixinOrAlipay.js";
import qs from "qs";
import config from "@/config/index.js";
import jwx from "@/common/jwx";
import store from "@/store/index.js";
export default async function recharge(
  urls,
  data = {},
  callback,
  offBfpayCDfalg = false
) {
  let promise;
  if (typeof callback !== "function") {
    promise = new Promise((resolve, reject) => {
      callback = function (resolvedata, rejectdata) {
        if (resolvedata) {
          resolve(resolvedata);
        } else {
          reject(rejectdata);
        }
      };
    });
  }

  let url = urls;
  if (typeof urls == "object") {
    url = IsWeixinOrAlipay() == "weixin" ? urls["weixin"] : urls["zfb"];
  }

  //#ifdef H5

  if (!offBfpayCDfalg) {
    let UArea = await store.dispatch("request/getRequest", {
      url: "/UArea",
    });
    UArea = UArea.length == 0 ? {} : UArea[0];
    if (UArea.b_sub == 4) {
      let str = window.location.href
        .replaceAll(":", "%3A")
        .replaceAll("/", "%2F")
        .replaceAll("?", "%3F")
        .replaceAll("=", "%3D");
      let CCBurl = "";
      if (["/WXCardxd", "/AlipayCard"].indexOf(url) >= 0) {
        CCBurl = "/CCBCard";
      } else if (["/WXCZxd", "/AlipayCZ"].indexOf(url) >= 0) {
        CCBurl = "/CCBCZ";
      } else {
        return await recharge(urls, data, callback, true);
      }
      let reqdata = {
        return_url: str,
        ...data,
      };
      let par = await uni.$z.request(CCBurl, {
        ...reqdata,
      });
      window.location.href = par;
    } else if (
      UArea.b_sub == 2 ||
      (IsWeixinOrAlipay() == "weixin" && UArea.b_sub == 3)
    ) {
      let BfpayCDurl = "/BfpayCZ";
      if (data.td && data.gtel) {
        BfpayCDurl =
          ["/WXCDxcxd", "/AlipayCDxc"].indexOf(url) >= 0
            ? "/BfpayCDxc"
            : "/BfpayCD";
      }
      if (["/WXCardxd", "/AlipayCard"].indexOf(url) >= 0) {
        BfpayCDurl = "/BfpayCard";
      }
      if (
        ["/BfpayTacdx", "/WXLlfAgentxd", "/AlipayLlfAgent"].indexOf(url) >= 0
      ) {
        BfpayCDurl = url;
      }

      let BfpayCD = await uni.$z.request(BfpayCDurl, {
        pageUrl: `${window.location.pathname}${window.location.hash}`,
        ...data,
        payType: IsWeixinOrAlipay() == "weixin" ? "0" : "1",
      });
      if (BfpayCD.length == 1 && BfpayCD[0].par == "succeed") {
        if (IsWeixinOrAlipay() == "weixin") {
          jwx.wxpay(JSON.parse(BfpayCD[0].qrCode), function () {
            callback(true);
          });
        } else {
          function ready(callback) {
            // 如果jsbridge已经注入则直接调用
            if (window.AlipayJSBridge) {
              callback && callback();
            } else {
              // 如果没有注入则监听注入的事件
              document.addEventListener("AlipayJSBridgeReady", callback, false);
            }
          }
          ready(function () {
            AlipayJSBridge.call("tradePay", {
              tradeNO: BfpayCD[0].qrCode,
            });
          });
        }
      } else {
        recharge(urls, data, callback, true);
      }
    } else {
      recharge(urls, data, callback, true);
    }
  } else if (IsWeixinOrAlipay() == "weixin") {
    let WXCZxd = await uni.$z.request(url, data);
    if (WXCZxd[0] == "err_JeError") {
      uni.showToast({
        title: "创建订单失败",
        duration: 2000,
        icon: "none",
      });
    } else {
      //#ifdef MP-WEIXINGH5
      WXCZxd[0].zfokpage = data.zfokpage;
      //#endif
      jwx.wxpay(WXCZxd[0], function () {
        callback(true);
      });
    }
  } else {
    let UArea = await uni.$z.request("/UArea");
    if (UArea[0].b_zfbmode == "1") {
      let par = await uni.$z.request(
        url,
        {
          ...data,
          b_app: 1,
        },
        "POST",
        "text"
      );
      console.log(par);

      function ready(callback) {
        // 如果jsbridge已经注入则直接调用
        if (window.AlipayJSBridge) {
          callback && callback();
        } else {
          // 如果没有注入则监听注入的事件
          document.addEventListener("AlipayJSBridgeReady", callback, false);
        }
      }
      ready(function () {
        AlipayJSBridge.call(
          "tradePay",
          {
            tradeNO: par,
          },
          function (result) {
            if (result.resultCode == "9000") {
              if (callback) {
                callback(true);
              }
            } else {
              uni.$u.toast("支付失败");
              window.location.href = `${config.baseURL}${url}?${qs.stringify(
                data
              )}`;
            }
          }
        );
      });
    } else {
      // console.log(`${config.baseURL}${url}?${qs.stringify(data)}`);
      window.location.href = `${config.baseURL}${url}?${qs.stringify(data)}`;
    }
  }
  //#endif

  return promise;
}
